package com.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangbowen
 * @date 2019/3/11
 **/
@Configuration
public class AmqpConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static final String ROUTING_KRY = "topic.test.*";
    public static final String DEAD_ROUTING_KRY = "dead.letter";

    @Bean
    public Exchange topicExchange() {
        return ExchangeBuilder.topicExchange("topicExchange").build();
    }

    @Bean
    public Exchange deadExchange() {
        return ExchangeBuilder.topicExchange("deadExchange").build();
    }

    @Bean
    public Queue deadQueue() {
        return QueueBuilder.nonDurable("deadQueue").build();
    }

    @Bean
    public Queue topQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl", 6000);
        arguments.put("x-dead-letter-exchange", "deadExchange");
        arguments.put("x-dead-letter-routing-key", DEAD_ROUTING_KRY);
        return QueueBuilder.nonDurable("topicQueue").withArguments(arguments).build();
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(topQueue()).to(topicExchange()).with(ROUTING_KRY).noargs();
    }

    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(DEAD_ROUTING_KRY).noargs();
    }

    @Bean
    public AsyncRabbitTemplate asyncRabbitTemplate() {
        return new AsyncRabbitTemplate(rabbitTemplate);
    }

   /* @Bean
    public RabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        //消费者线程（需要在客服端和消费者之间进行线程切换）
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        //客户端线程
        //  DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(customMessageConverter);
        //    factory.setTaskExecutor(new ThreadPoolExecutor(3, 3, 6, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1)));
        //factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        // factory.setConcurrentConsumers(5);
        //factory.setMaxConcurrentConsumers(5);
        return factory;
    }*/
}
